import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { TimeConfigClass } from '../../common/common-config';
import { StorageService } from "../../common/storage.service";
import { ArticleService } from './article.service';

@Component({
  selector: 'add',
  templateUrl: './articleAdd.component.html',
  // styleUrls: ['./articleList.component.css'],
  providers: [ArticleService]
})
export class ArticleAddComponent implements OnInit {
  //列表
  timeConfig: any = new TimeConfigClass(); // 时间空间初始化

  constructor(private storage: StorageService, private route: ActivatedRoute, private router: Router, private server: ArticleService) {  }

  title: string = '新建';
  objToSubmit: any = {}; // 提交集合
  objToPost: any = {}; 

  siteArr: any = []; //网站
  templateArr: any = []; // 模板
  tree: any[] = []; //目录
  selectedFiles: any = [];;

  uploadRrl: String = 'commFiles/upload/api?category=FILE_BJ17888'; // 上传图片地址
  imageArr = [];  //标题照片
  onlyImg: String  = 'true'; //图片是否单张

  weParam: String = ''; //文本编辑器参数

  ngOnInit() {
    //this.templateArr = [{code:"11111",name:"测试"},{code:"2222",name:"测试22"}]
    this.objToPost = {};
    this.route.params.subscribe((params) => {
      let id = params.id
      if(!id || id<1 ){
        this.onlyImg = 'false'; //新增时允许多张上传
        return false;
      }
      //获取数据
      this.get(id);
    });
    this.uploadRrl = this.server.httpService.baseUrl + this.uploadRrl;
    this.findSite();
  }
	
	//返回
  returnBtn() {
    this.router.navigate(['../../article'], { relativeTo: this.route });
  }
    
  /**
   * 保存
   */
  save(ev) {
    let params = this.objToPost;
    params.picture = params.image
    params.catalogCode = this.selectedFiles ? this.selectedFiles.code  : '';
    //参数验证
    if(!this.checkParams(params)){
      return false;
    }
    console.log(params)
    this.storage.loading();
    this.server.save(params).then(data => {
      this.storage.loadout();
      if (data.result) {
        this.storage.messageService.emit({ severity: 'success', detail: data.msg });
        if(ev == '1' && (!params.picture || params.picture.indexOf(',') < 0)){
          this.get(data.data);
        }else{
          this.router.navigate(['../../article'], { relativeTo: this.route });
        }
        console.log('保存成功')
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'保存失败' })
        console.log('保存失败')
      }
    });
  }

  /**
   * 参数校验
   */
  checkParams(params) {
      let  detail = '';
      if(!params.name){
        detail = '名称';
      }else if(!params.id && !params.siteCode){
        detail = '网站';
      }else if(!params.id && !params.catalogCode){
        detail = '目录';
      }else if(!params.templateCode){
        detail = '模板';
      }else{
        return true;
      }
      this.storage.messageService.emit({ severity: 'warn', detail: detail+'不能为空！' })
      return false;
  }

  /**
   * 获取数据
   */
  get(id) {
    this.server.get({id:id}).then(data => {
      if (data.result) {
        this.objToPost = data.data;
        this.objToPost.image = this.objToPost.picture
        //图片
        //this.imageArr.unshift({ code: params.siteCode , label: '首页','children':[] });
        this.imgUrlData(data.data.picture, 'imageArr', 'true');
        //富文本
        this.weParam = '&tP=' + this.objToPost.tP ;
        this.initIframeObj(null);  
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'请求失败!记录不存在或已被删除' })
      }
    });
  }

   /**
   * 获取网站
   */
  findSite() {
    let params = {};
    this.server.findSite(params).then(data => {
      if (data.result) {
        this.siteArr = data.data
        this.objToPost.siteCode = this.siteArr[0].code;
        this.getTemplateArr();
        this.findTree();
        console.log('获取网站成功')
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'获取网站失败' })
        console.log('获取网站失败')
      }
    });
  }

  /**
   * 获取模板列表
   */
  getTemplateArr() {
    let params = {};
    this.server.getTemplateArr(params).then(data => {
      if (data.result) {
        this.templateArr = data.data
        this.templateArr.unshift({ code: '', name: '请选择' });
        console.log('保存成功')
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'保存失败' })
        console.log('保存失败')
      }
    });
  }

  /**
   * 获取目录
   */
  findTree() {
    const params = Object.assign(this.objToPost);
    this.server.findTree(params).then(data => {
      if (data.result) {
        let dat = data.data
        dat.unshift({ code: params.siteCode , label: '首页','children':[] });
        this.expandAll(dat);
        this.tree = dat;
        console.log('获取目录成功')
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'获取目录失败' })
        console.log('获取目录失败')
      }
    });
  }

  /**
   * 
   * @param data 树
   */
  expandAll(data){
    data.forEach( node => {
      this.expandRecursive(node, true);
    } );
  }

  private expandRecursive(node, isExpand:boolean){
    node.expanded = isExpand;
    if(node.children){
      node.children.forEach( childNode => {
        this.expandRecursive(childNode, isExpand);
      } );
    } 
  }

  
  /**
  * 上传单张图片验证
  */
  onSelect(event, obj) {
    if (obj.onlyImg == 'true' && event.files.length > 1) {
      this.storage.messageService.emit({ severity: 'warn', detail:'只能选择一张图片！' })
      obj.clear();
      return false;
    }
    event.upload();
  }

  /**
  * 图片上传回调函数
  * @param event
  * @param f
  */
  onUpload(event, f) {
    const result = JSON.parse(event.xhr.responseText);
    console.log('上传图片', result);
    if (result && result.result && result.data) {
    	let path = '';
    	result.data.forEach( item => {
        	path += ',' + item.path;
      });
      if(path.length>0){
      	path = path.substring(1,path.length)
      }
      this.objToPost[f.cancelLabel] = (this.objToPost[f.cancelLabel] && f.onlyImg != 'true') ? this.objToPost[f.cancelLabel] + ',' + path : path;
      this.imgUrlData(path, f.cancelLabel + 'Arr', f.onlyImg);
    };
  }
  
  /**
   * 展示图片数据
   */
  imgUrlData(fileUrl: string, fileArr: any, isClear?: string) {
    if (!fileUrl || !fileArr) {
      return false;
    };
    if (isClear == undefined || isClear == 'true') {
      this[fileArr] = [];
    };
    for (let item of fileUrl.split(',')) {
      this[fileArr] = [...this[fileArr], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    };
  }
  /**
  *删除图片并更新对应的图片数据
  * @param event
  * @param f
  */
  removeItem(event, f) {
    //console.log(f);
    let codeArray = this.objToPost[f].split(',');
    codeArray.splice(event.index, 1);
    this.objToPost[f] = codeArray.join(',');
    this[f + 'Arr'] = this[f + 'Arr'].filter((val, index) => index !== event.index);
  }

  /*
   * 初始化iframe页面
   */
  initIframeObj(iframeObj){
    this.weParam +=  ('&reqUrl=' + this.server.httpService.baseUrl);
    iframeObj = document.getElementById('myrame');
    iframeObj.src += this.weParam;
  }

}
